package fishBids.group3.behaviour;

import jade.content.Concept;
import jade.content.ContentElement;
import jade.content.lang.Codec;
import jade.content.onto.Ontology;
import jade.content.onto.basic.Action;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import es.upm.agents.ontology.ProductType;
import es.upm.agents.ontology.ToGetPrice;
import es.upm.agents.ontology.ToGetPriceResponse;
import fishBids.group3.common.Constants;
import fishBids.group3.utils.Utils;

public class GetPriceBehaviour extends SimpleBehaviour {
	
	public GetPriceBehaviour(Agent agent, Codec codec, Ontology ontology, AID market, ProductType productType){
		this.creatorAgent = agent;
		this.codec = codec;
		this.ontology = ontology;
		this.market = market;
		this.productType = productType;
	}


	/**
	 * 
	 */
	private static final long serialVersionUID = 1406893628948849472L;

	@Override
	public void action() {

		if(status == 0){
			ToGetPrice toGetPrice = new ToGetPrice();
			toGetPrice.setProductType(productType);
	
			Utils.sendMessageWithConcept(ACLMessage.QUERY_REF, codec, ontology, market, Constants.GET_PRICE, myAgent, toGetPrice);
	
			// Waits for the arrival of an answer
//			System.out.println("Bidder >>>> Sending get Price request, waiting for an INFORM or REFUSE message");
			status = 1;
		}
		// Receive the message
		ACLMessage msg = creatorAgent.receive(MessageTemplate.and(
				MessageTemplate.MatchPerformative(ACLMessage.INFORM),
				MessageTemplate.MatchProtocol(Constants.GET_PRICE) )); 
		
		if(msg != null ){

			try {
				ContentElement ce = null;
				if (msg.getPerformative() == ACLMessage.INFORM) {
					//System.out.println("INFORM message arrived from Market");
					ce = creatorAgent.getContentManager().extractContent(msg);
					if (ce instanceof Action) {
						Action ac = (Action) ce;
						Concept cpt = ac.getAction();
						if (cpt instanceof ToGetPriceResponse) {
							ToGetPriceResponse toGetPriceResponse = (ToGetPriceResponse) cpt;
//							System.out.println(creatorAgent.getName()
//									+ " received new product of type: "
//									+ toGetPriceResponse.getProductType().getType() + " with price: "
//									+ toGetPriceResponse.getPrice());
							end = true;
						}
					}
					return;
				}
				if (msg.getPerformative() == ACLMessage.NOT_UNDERSTOOD) {
//					System.out.println(creatorAgent.getName()
//							+ " got a NOT_UNDERSTOOD in getPrice, check!!!!! :(");
					end = true;
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		}else {
			block();
		}

	}

	@Override
	public boolean done()

	{
		return end;
	}
	
	/* flag to state if the behaviour stops */
	boolean end = false;
	
	/* Market agent */
	AID market;
	ProductType productType;
	
	/*agent creator of this behaviour*/
	Agent creatorAgent;
	private Codec codec; 
	private Ontology ontology; 	
	int status = 0;


}

